# -*- coding: utf-8 -*-
import json
import sys

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *
from PyQt5.QtGui import *

from client.pages.LoginWin import *
from client.func.ClientHttp import login_post

root = "./"


class LoginPage(QMainWindow, Ui_LoginWin):
    """登陆界面"""
    login_signal = pyqtSignal(str)  # 切换登录后界面信号
    register_signal = pyqtSignal()  # 切换注册界面信号

    def __init__(self):
        super(LoginPage, self).__init__()
        self.setupUi(self)
        self.config = self.LoadConfig(root + "client/.cache/config.json")
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.pswd_text.setEchoMode(QtWidgets.QLineEdit.Password)
        self.user_combox.addItems(list(self.config["User"].keys()))

        self.close_button.clicked.connect(self.OnClose)
        self.login_button.clicked.connect(self.OnLogin)
        self.register_button.clicked.connect(self.OnRegister)
        self.user_combox.activated.connect(self.ChooseUser)
        self.eye_button.pressed.connect(self.EyePressed)
        self.eye_button.released.connect(self.EyeRelease)

    def formatCheck(self):
        if not self.user_combox.currentText():
            self.info_label.setText(u"用户名不能为空！")
            return False
        elif not self.user_combox.currentText().isdigit():
            self.info_label.setText(u"用户名必须为纯数字！")
            return False
        elif not self.pswd_text.text():
            self.info_label.setText(u"密码不能为空！")
            return False
        else:
            self.info_label.setText(u"")
            return True

    def OnLogin(self):
        if not self.formatCheck():
            return
        self.info_label.setText(u"登陆中...")
        status, info = login_post(self.user_combox.currentText(), self.pswd_text.text())
        if status:  # 登陆验证成功
            if self.save_pswd.isChecked():
                self.config["User"][self.user_combox.currentText()] = self.pswd_text.text()
            else:
                if self.user_combox.currentText() in list(self.config["User"].keys()):
                    del self.config["User"][self.user_combox.currentText()]
            self.SaveConfig(root + "client/.cache/config.json")
            self.info_label.setText(info)
            self.login_signal.emit(self.user_combox.currentText())
        else:
            self.info_label.setText(info)


    def OnRegister(self):
        self.register_signal.emit()

    def ChooseUser(self):
        try:
            self.pswd_text.setText(self.config["User"][self.user_combox.currentText()])
            self.save_pswd.setChecked(True)
        except:
            pass

    def EyePressed(self):
        self.pswd_text.setEchoMode(QtWidgets.QLineEdit.Normal)

    def EyeRelease(self):
        self.pswd_text.setEchoMode(QtWidgets.QLineEdit.Password)

    def LoadConfig(self, path):
        try:
            with open(path, "r", encoding='utf-8') as f:
                return json.load(f)
        except:
            return {
                "User": {}, "sound": 50
            }

    def SaveConfig(self, path):
        with open(path, "w") as f:
            f.write(json.dumps(self.config))

    def OnClose(self):
        self.close()


if __name__ == "__main__":
    root = "../../"
    app = QApplication(sys.argv)
    myWin = LoginPage()
    myWin.show()
    sys.exit(app.exec_())
